package cn.gary.oaserver.controller;

import cn.gary.oaserver.config.security.UserDetailImpl;
import cn.gary.oaserver.config.utils.JwtToken;
import cn.gary.oaserver.entity.TAdmin;
import cn.gary.oaserver.params.LoginParam;
import cn.gary.oaserver.params.Result;
import cn.gary.oaserver.service.ITAdminService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 邓必宏
 * @title:
 * @Demo:
 * @DateTime: 2024/3/15
 */

@RestController
public class LoginController {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    ITAdminService adminService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    UserDetailImpl userDetail;

    @Autowired
    JwtToken jwtToken;


    @PostMapping("/login")
    @ApiOperation("登录方法")
    public Result login(@RequestBody LoginParam param,HttpServletRequest request) {

        if (!(param.getCode ()==request.getSession ().getAttribute ( "captcha" ))) {
            Result.error ( "验证码有误！" );
        }
        TAdmin admin = null;
        try {
            admin = (TAdmin) userDetail.loadUserByUsername ( param.getUsername ( ) );
        } catch (UsernameNotFoundException e) {
            Result.error ( "用户名不存在！" );
        }
        //判断密码是否正确
//        if (passwordEncoder.matches ( param.getPassword ( ), admin.getPassword ( ) )) {
//            return Result.error ( "密码错误!" );
//        }

        //判断当前用户是否禁用
        if (!admin.isEnabled ( )) {
            return Result.error ( "账号被禁用，请联系管理员!" );
        }

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken ( admin, null, admin.getAuthorities ( ) );

        SecurityContextHolder.getContext ( ).setAuthentication ( token );

        String jToken = jwtToken.createToken ( admin );

        Map map = new HashMap ( );
        map.put ( "token", jwtToken.tokenHead+jToken );
        map.put ( "admin", admin );
        return Result.success ( "登录成功！", map );
    }

    @PostMapping("/logout")
    @ApiOperation("退出登录方法")
    public Result loginOut() {
        Integer adminId = ((TAdmin)(SecurityContextHolder.getContext().getAuthentication().getPrincipal())).getId();
        // 2、从redis中删除当前登录用户的菜单列表数据
        redisTemplate.delete("menu_" + adminId);
        return Result.success ( "注销成功" );
    }


    @GetMapping("/admin/info")
    @ApiOperation("用户信息")
    public Result userInfo(Principal principal) {
        if (principal == null) {
            return Result.error ( "请先登录" );
        }
        Map<String,Object> map=new HashMap<>();
        TAdmin admin = (TAdmin) userDetail.loadUserByUsername ( principal.getName ( ) );
        admin.setPassword ( null );
        List<String> permissions= adminService.getMenuUrlByAdminId(admin.getId ());
        map.put ( "user",admin );
        map.put ( "permis",permissions );
        //获取当前登录用户的所有角色列表
        return Result.success ( "返回数据成功", map );
    }

}
